
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using Apps.IDAL.Sys;
using Apps.Models.Sys;
using Apps.IBLL.Sys;
namespace Apps.BLL.Sys
{
	public partial class SysUserConfigBLL: Virtual_SysUserConfigBLL,ISysUserConfigBLL
	{
        

	}
	public class Virtual_SysUserConfigBLL
	{
        [Dependency]
        public ISysUserConfigRepository m_Rep { get; set; }

		public virtual List<SysUserConfigModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<SysUserConfig> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
								a=>a.Id.Contains(queryStr)
								|| a.Name.Contains(queryStr)
								|| a.Value.Contains(queryStr)
								|| a.Type.Contains(queryStr)
								
								|| a.UserId.Contains(queryStr)
								);
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

		public virtual List<SysUserConfigModel> GetListByParentId(ref GridPager pager, string queryStr,object parentId)
        {
			return new List<SysUserConfigModel>();
		}

        public virtual List<SysUserConfigModel> CreateModelList(ref IQueryable<SysUserConfig> queryData)
        {

            List<SysUserConfigModel> modelList = (from r in queryData
                                              select new SysUserConfigModel
                                              {
													Id = r.Id,
													Name = r.Name,
													Value = r.Value,
													Type = r.Type,
													State = r.State,
													UserId = r.UserId,
          
                                              }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, SysUserConfigModel model)
        {
            try
            {
                SysUserConfig entity = m_Rep.GetById(model.Id);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new SysUserConfig();
               				entity.Id = model.Id;
				entity.Name = model.Name;
				entity.Value = model.Value;
				entity.Type = model.Type;
				entity.State = model.State;
				entity.UserId = model.UserId;
  

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }



         public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
       

        public virtual bool Edit(ref ValidationErrors errors, SysUserConfigModel model)
        {
            try
            {
                SysUserConfig entity = m_Rep.GetById(model.Id);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                              				entity.Id = model.Id;
				entity.Name = model.Name;
				entity.Value = model.Value;
				entity.Type = model.Type;
				entity.State = model.State;
				entity.UserId = model.UserId;
 


                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

      

        public virtual SysUserConfigModel GetById(object id)
        {
            if (IsExists(id))
            {
                SysUserConfig entity = m_Rep.GetById(id);
                SysUserConfigModel model = new SysUserConfigModel();
                              				model.Id = entity.Id;
				model.Name = entity.Name;
				model.Value = entity.Value;
				model.Type = entity.Type;
				model.State = entity.State;
				model.UserId = entity.UserId;
 
                return model;
            }
            else
            {
                return null;
            }
        }


		 /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<SysUserConfigModel> list,ref ValidationErrors errors )
        {
          
            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
			 				 excelFile.AddMapping<SysUserConfigModel>(x => x.Name, "Name");
				 excelFile.AddMapping<SysUserConfigModel>(x => x.Value, "Value");
				 excelFile.AddMapping<SysUserConfigModel>(x => x.Type, "Type");
				 excelFile.AddMapping<SysUserConfigModel>(x => x.State, "State");
				 excelFile.AddMapping<SysUserConfigModel>(x => x.UserId, "UserId");
 
            //SheetName
            var excelContent = excelFile.Worksheet<SysUserConfigModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new SysUserConfigModel();
						 				  entity.Id = row.Id;
				  entity.Name = row.Name;
				  entity.Value = row.Value;
				  entity.Type = row.Type;
				  entity.State = row.State;
				  entity.UserId = row.UserId;
 
                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<SysUserConfigModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        SysUserConfig entity = new SysUserConfig();
                       						entity.Id = ResultHelper.NewId;
						entity.Name = model.Name;
						entity.Value = model.Value;
						entity.Type = model.Type;
						entity.State = model.State;
						entity.UserId = model.UserId;
 
                        db.SysUserConfig.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
		  public void Dispose()
        { 
            
        }

	}
}
